import time

from info import constants, db
from info.news import new_blue
from flask import render_template, current_app, session, request, jsonify, g, abort, make_response, redirect, url_for

from ..models1 import News, Category


@new_blue.route('/')
def new():
    categories = Category.query.all()
    categories_list = []
    for categorie in categories:
        categories_list.append(categorie.to_dict())

    data = {

        'categories': categories_list,
        'oldid': int(request.cookies.get('cid')) - 1 if request.cookies.get('cid') else 0

    }
    # print(data['oldid'],'-------')
    resp = make_response(render_template('new_list.html', data=data))
    if request.cookies.get('cid'):
        resp.set_cookie('old', '1')
    # return render_template('new_list.html',data=data)
    return resp


@new_blue.route('/news_list')
def news_list():
    # 获取新闻获取请求
    args_dict = request.args
    cid = args_dict.get('cid', '1')
    page = args_dict.get('page', '1')
    per_page = args_dict.get('per_page', constants.HOME_PAGE_MAX_NEWS)
    # 判断是否第一次接入
    if request.cookies.get('old') == '1':
        cid = request.cookies.get('cid')

    try:
        page = int(page)
        per_page = int(per_page)
    except:
        pass
    # 打开数据库
    try:
        if cid == '1':
            paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,
                                                                                                             per_page,
                                                                                                             False)
        elif cid != '8':
            paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,
                                                                                                             per_page,
                                                                                                             False)
        else:
            paginate = News.query.order_by(News.clicks.desc()).paginate(page, per_page, False)
        # 获取到的总资源
        items = paginate.items
        # 获取到总页数
        total_page = paginate.pages
        current_page = paginate.page
    except:
        pass
    news_li = []
    # 获取每一个数据的详细数据
    for new in items:
        news_li.append(new.to_dict())
    # print(news_li)
    data = {
        'total_page': total_page,
        'cur_page': current_page,
        'news_dict_li': news_li
    }
    # 返回json数据，并构造cookie
    data = jsonify(errno=0, data=data)
    resp = make_response(data)
    resp.set_cookie('cid', args_dict.get('cid', '1'))
    resp.set_cookie('old', '0')
    return resp
    # return jsonify(errno=0, data=data)


@new_blue.route('/<int:new_id>')
def news_id(new_id):
    # 获得新闻对象
    data = News.query.get(new_id)
    if not data:
        abort(404)
    # 新闻点击加1
    data.clicks += 1
    db.session.commit()

    time.sleep(0.1)
    news = data.to_dict()

    data = {

        "news": news,

    }
    return render_template('new_show.html', data=data)


@new_blue.route('/news_add')
def new_add():
    # 获得新闻对象
    id = request.args.get('id')
    move = request.args.get('move')
    data = News.query.get(id)
    category_id = data.category_id
    if move == 'up':
        data = News.query.filter(News.category_id == category_id).order_by(News.create_time.asc()).filter(
            News.create_time > data.create_time).first()
    if move == 'down':
        data = News.query.filter(News.category_id == category_id).order_by(News.create_time.desc()).filter(
            News.create_time < data.create_time).first()
        # 新闻点击加1

    if not data:
        print('ok-------')
        return jsonify(errno='1')
        #
        # news = data.to_dict()
        # data = {
        #
        #     "news": news
        #
        # }
        # return jsonify(data=data)
    # 新闻点击加1

    data.clicks += 1

    news = data.to_dict()

    data = {

        "news": news

    }
    db.session.commit()

    return jsonify(data=data)
